/*
 *   Copyright 2021 zzh
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.aduib.boot.common.asm;

import com.aduib.boot.common.exception.CommonException;
import com.aduib.boot.common.util.ClassUtils;
import com.aduib.boot.common.util.IOUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import java.lang.reflect.Executable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 查找一个类的所有形式参数名
 *
 * @description: CustomClassVisitor
 * @author: zzh
 * @date: 2021/10/20 09:46
 */
public class ParameterNameVisitor extends ClassVisitor implements Opcodes {

  private static final String STATIC_CLASS_INIT = "<clinit>";

  private final Map<Executable, String[]> executableMap;

  private final Class<?> clazz;

  public ParameterNameVisitor(Map<Executable, String[]> executableMap, Class<?> clazz) {
    super(ASM5);
    this.executableMap = executableMap;
    this.clazz = clazz;
  }

  public ParameterNameVisitor(Class<?> clazz) {
    this(new HashMap<>(), clazz);
  }

  private static boolean isSyntheticOrBridged(int access) {
    return (((access & Opcodes.ACC_SYNTHETIC) | (access & Opcodes.ACC_BRIDGE)) > 0);
  }

  private static boolean isStatic(int access) {
    return ((access & Opcodes.ACC_STATIC) > 0);
  }

  public String[] parameterNames(Executable executable) {
    if (executableMap.isEmpty()) {
      buildParameters();
    }
    return executableMap.get(executable);
  }

  public void buildParameters() {
    String classFilePath = ClassUtils.getClassFilePath(clazz);
    try {
      ClassReader classReader =
          new ClassReader(IOUtils.readBytes(new URL(classFilePath).openStream()));
      classReader.accept(new ParameterNameVisitor(executableMap, clazz), null, 0);
    } catch (Exception ignore) {
    }
  }

  @Override
  public MethodVisitor visitMethod(
      int access, String name, String descriptor, String signature, String[] exceptions) {
    if (!isSyntheticOrBridged(access) && !STATIC_CLASS_INIT.equals(name)) {
      return new LocalVariableTableVisitor(
          executableMap, this.clazz, name, descriptor, isStatic(access));
    }
    return null;
  }

  public static class LocalVariableTableVisitor extends MethodVisitor {

    private static final String CONSTRUCTOR = "<init>";

    private final Map<Executable, String[]> executableMap;

    private final Class<?> clazz;

    private final String name;

    private final String[] parameterNames;

    private final Type[] parameterTypes;

    /** 是否是静态方法 */
    private final boolean isStatic;
    private final int[] lvtSlotIndex;
    /** 是否有本地变量表 */
    private boolean hasLvtInfo = false;

    public LocalVariableTableVisitor(
        Map<Executable, String[]> executableMap,
        Class<?> clazz,
        String name,
        String descriptor,
        boolean isStatic) {
      super(ASM5);
      this.executableMap = executableMap;
      this.clazz = clazz;
      this.name = name;
      this.parameterTypes = Type.getArgumentTypes(descriptor);
      this.parameterNames = new String[parameterTypes.length];
      this.isStatic = isStatic;
      this.lvtSlotIndex = computeLvtSlotIndices(isStatic, parameterTypes);
    }

    private static int[] computeLvtSlotIndices(boolean isStatic, Type[] paramTypes) {
      int[] lvtIndex = new int[paramTypes.length];
      int nextIndex = (isStatic ? 0 : 1);
      for (int i = 0; i < paramTypes.length; i++) {
        lvtIndex[i] = nextIndex;
        if (isWideType(paramTypes[i])) {
          nextIndex += 2;
        } else {
          nextIndex++;
        }
      }
      return lvtIndex;
    }

    private static boolean isWideType(Type aType) {
      return (aType == Type.LONG_TYPE || aType == Type.DOUBLE_TYPE);
    }

    @Override
    public void visitLocalVariable(
        String name, String descriptor, String signature, Label start, Label end, int index) {
      this.hasLvtInfo = true;
      for (int i = 0; i < this.lvtSlotIndex.length; i++) {
        if (this.lvtSlotIndex[i] == index) {
          this.parameterNames[i] = name;
        }
      }
    }

    @Override
    public void visitEnd() {
      if (this.hasLvtInfo || (this.isStatic && this.parameterNames.length == 0)) {
        this.executableMap.put(resolveExecutable(), this.parameterNames);
      }
    }

    private Executable resolveExecutable() {
      ClassLoader loader = this.clazz.getClassLoader();
      Class<?>[] argTypes = new Class<?>[this.parameterTypes.length];
      for (int i = 0; i < this.parameterTypes.length; i++) {
        argTypes[i] = ClassUtils.forName(this.parameterTypes[i].getClassName(), loader);
      }
      try {
        if (CONSTRUCTOR.equals(this.name)) {
          return ClassUtils.getConstructor(clazz,argTypes);
        }
        return this.clazz.getDeclaredMethod(this.name, argTypes);
      } catch (NoSuchMethodException ex) {
        throw new CommonException(
            "Method ["
                + this.name
                + "] was discovered in the .class file but cannot be resolved in the class object",
            ex);
      }
    }
  }
}
